package com.ys.controller.api.finance;

import com.ys.config.MenuId;
import com.ys.entity.finance.TcwWanliCurrencyExchange;
import com.ys.entity.sys.YsCol;
import com.ys.service.finance.TcwWanliCurrencyExchangeService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 货币兑换单
 */
@Controller
@RequestMapping("/api/inter/tcwWanliCurrencyExchange")
public class ApiInterTcwWanliCurrencyExchangeController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwWanliCurrencyExchangeController.class);

    @Autowired
    private CommonApiService<TcwWanliCurrencyExchange> commonApiService;

    @Autowired
    private TcwWanliCurrencyExchangeService tcwWanliCurrencyExchangeService;

    @Autowired
    private YspTaskService yspTaskService;


    @RequiresPermissions("tcwWanliCurrencyExchange:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TcwWanliCurrencyExchange cond,String conditions){
        String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");
        if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
            cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
        }
        cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS updateTime1")//审核时间
        .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
                .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
        .addLeftJoin("TCW_DepositPlatform tda ON tda.id = A.DepositAccountId ")//收款平台
             .addField("tda.code AS depositAccountCode,tda.name AS depositAccountName,tda.platformName AS platformName")
        .addLeftJoin("TB_CompanyInfo tci ON tci.vid = tda.CompanyVid ")//公司
                .addField("tci.vname AS companyName")
        .addLeftJoin("TCW_WanliCurrencyExchangeItem tce ON tce.CurrencyExchangeBid = A.Bid ")//货币兑换子件
                .addField("tce.hcCurrency AS hcCurrency,tce.hcAmount AS hcAmount, tce.hrCurrency AS hrCurrency ,tce.hrAmount AS hrAmount,tce.exchangeRate AS exchangeRate");
        return commonApiService.searchLay(cond);
    }


    /**
     * 新增
     */
    @RequiresPermissions("tcwWanliCurrencyExchange:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("货币兑换单新增传参：" + params);
            //修改
            return tcwWanliCurrencyExchangeService.add(params,subData);
        } catch (Exception e) {
            logger.error("货币兑换单新增出错：", e.getMessage(), e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions("tcwWanliCurrencyExchange:add")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("货币兑换单修改传参：" + params);
            //修改
            return tcwWanliCurrencyExchangeService.edit(params,subData);
        } catch (Exception e) {
            logger.error("货币兑换单修改出错：", e.getMessage(), e);
            return R.error(e.getMessage());
        }
    }


    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwWanliCurrencyExchangeService.flowPass(id, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        TcwWanliCurrencyExchange entity = new TcwWanliCurrencyExchange().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("万里汇货币兑换单驳回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 流转驳回
     */
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        TcwWanliCurrencyExchange entity = new TcwWanliCurrencyExchange().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("万里汇货币兑换单驳回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/toDel")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            return tcwWanliCurrencyExchangeService.del(id);
        } catch (Exception e) {
            logger.error("删除万里汇货币兑换单出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwWanliCurrencyExchange cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");
            if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
                cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
            }
            cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                    .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS updateTime1")//审核时间
                    .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
                    .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
                    .addLeftJoin("TCW_DepositPlatform tda ON tda.id = A.DepositAccountId ")//收款平台
                    .addField("tda.code AS depositAccountCode,tda.name AS depositAccountName,tda.platformName AS platformName")
                    .addLeftJoin("TB_CompanyInfo tci ON tci.vid = tda.CompanyVid ")//公司
                    .addField("tci.vname AS companyName")
                    .addLeftJoin("TCW_WanliCurrencyExchangeItem tce ON tce.CurrencyExchangeBid = A.Bid ")//货币兑换子件
                    .addField("tce.hcCurrency AS hcCurrency,tce.hcAmount AS hcAmount, tce.hrCurrency AS hrCurrency ,tce.hrAmount AS hrAmount,tce.exchangeRate AS exchangeRate");
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_WanliCurrencyExchange)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TcwWanliCurrencyExchange> util = new ExportExcelUtils<>(new TcwWanliCurrencyExchange());
            String toFilePath = util.exportExcel(listData, listField, "万里汇货币兑换单报表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

}
